from logging.handlers import RotatingFileHandler
from flask_session import Session
from flask import Flask, g, render_template
from redis import StrictRedis
from flask_wtf import CSRFProtect, csrf
from config import configs
import logging
from flask_sqlalchemy import SQLAlchemy
import pymysql


pymysql.install_as_MySQLdb()


db = SQLAlchemy()
# 当python中的变量设置为None时，我们可以在注释信息中通过type来设置变量的类型，让python解释器知道该变量的类型
redis_store = None  # type: StrictRedis


def create_app(config_name):
    """创建app"""

    config_class = configs[config_name]

    setup_log(config_class.LOGGING_LEVEL)

    app = Flask(__name__)

    app.config.from_object(config_class)

    db.init_app(app)

    global redis_store
    redis_store = StrictRedis(config_class.REDIS_HOST, config_class.REDIS_PORT, decode_responses=True)

    CSRFProtect(app)

    from info.modules.index import index_blue
    app.register_blueprint(index_blue)
    from info.modules.passport import passport_blue
    app.register_blueprint(passport_blue)
    from info.modules.news import news_blue
    app.register_blueprint(news_blue)
    from info.utils.common import do_index_class
    app.add_template_filter(do_index_class, 'indexClass')
    from info.modules.user import user_blue
    app.register_blueprint(user_blue)
    from info.modules.admin import admin_blue
    app.register_blueprint(admin_blue)

    from info.utils.common import user_login_data
    @app.errorhandler(404)
    @user_login_data
    def page_not_found(_):
        """404接口函数"""
        user = g.user
        context = {'user': user.to_dict() if user else None}
        return render_template('news/404.html', context=context)
        return app

    @app.after_request
    def set_csrf_token(response):
        """每一次请求前设置csrf_token"""
        csrf_token = csrf.generate_csrf()
        response.set_cookie('csrf_token', csrf_token)
        return response

    Session(app)

    return app


def setup_log(level):
    """设置日志"""
    logging.basicConfig(level=level)

    file_log_handler = RotatingFileHandler("logs/log", maxBytes=1024 * 1024 * 100, backupCount=10)

    formatter = logging.Formatter('%(levelname)s %(filename)s:%(lineno)d %(message)s')

    file_log_handler.setFormatter(formatter)

    logging.getLogger().addHandler(file_log_handler)
